package com.ews.onlineexchange.service.startup;

import java.util.HashMap;
import java.util.Map;

import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.ews.onlineexchange.service.EmailService;
import com.google.gson.Gson;

public class SmsMessageListener implements MessageListener{
	private Gson gson=new Gson();
	@Override
	public boolean dealMessage(Message message) {

//		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//消息的几个关键值
//		System.out.println("message receiver time from mns:" + format.format(new Date()));
//		System.out.println("message handle: " + message.getReceiptHandle());
//		System.out.println("message body: " + messageBodyAsString);
//      System.out.println("message id: " + message.getMessageId());
//      System.out.println("message dequeue count:" + message.getDequeueCount());
//      System.out.println("Thread:" + Thread.currentThread().getName());
        String messageBodyAsString = message.getMessageBodyAsString();
		
        try{
        	Map<String,Object> contentMap = gson.fromJson(messageBodyAsString, HashMap.class);
        	
        	System.out.println(messageBodyAsString);
			//TODO 根据文档中具体的消息格式进行消息体的解析
            Boolean success = (Boolean)contentMap.get("success");
            System.out.println("标志："+success);
            if(!success) {
            	EmailService emailService = new EmailService();
            	emailService.sendFailNotification(messageBodyAsString);
            	return true;
            }else {
            	System.out.println("处理完成");
            	return true;
            }
        }catch(com.google.gson.JsonSyntaxException e){
        	System.out.println("error_json_format:"+messageBodyAsString);
			//理论上不会出现格式错误的情况，所以遇见格式错误的消息，只能先delete,否则重新推送也会一直报错
			return true;
        } catch (Throwable e) {
			//您自己的代码部分导致的异常，应该return false,这样消息不会被delete掉，而会根据策略进行重推
        	e.printStackTrace();
			return false;
		}
//		//消息处理成功，返回true, SDK将调用MNS的delete方法将消息从队列中删除掉
//		return true;
	}
}
